﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Workflow.ComponentModel;
using System.Diagnostics;
using System.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.ComponentModel.Design;
using System.Linq.Expressions;

namespace TextFlow.Activities
{
	public class StoreVariableActivity : Activity
	{
        public StoreVariableActivity()
        {
        }

        public StoreVariableActivity( string name ) : base( name )
        {
        }

        public string LHS { get; set; }
        public Expression RHS { get; set; }     // can't serialize dynamic delegates, else we'd just compile this once and store the delegate itself...

        protected override ActivityExecutionStatus Execute( ActivityExecutionContext aec )
        {
            Debug.Assert( string.IsNullOrEmpty( LHS ) == false );
            Debug.Assert( RHS != null );

            TextFlowWorkflow root = this.GetActivityByName( "MainFlow", false ) as TextFlowWorkflow;

            Debug.Assert( root != null );

            ServiceLookupDelegate svclookup = delegate( Type t )
            {
                if ( t == typeof( TextFlowWorkflow ) )
                {
                    return root;
                }
                else
                {
                    return aec.GetService( t );
                }
            };

            object result = Utils.ComputeResult( RHS, svclookup );

            root.Operands[ LHS ] = result;

            return ActivityExecutionStatus.Closed;
        }
    }
}
